/**
 * 仪表板页面
 * 
 * 显示系统概览和关键指标
 */

import React, { useEffect } from 'react'
import { useQuery } from 'react-query'
import { 
  Database, 
  Code, 
  Activity, 
  Users,
  TrendingUp,
  AlertTriangle,
  CheckCircle,
  Clock
} from 'lucide-react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { monitoringApi, dataSourceApi, apiManagementApi } from '@/services/api'
import { useMonitoringStore } from '@/store'
import { formatNumber, formatPercentage, formatDateTime } from '@/lib/utils'

// 统计卡片组件
interface StatCardProps {
  title: string
  value: string | number
  change?: string
  icon: React.ComponentType<{ className?: string }>
  trend?: 'up' | 'down' | 'neutral'
}

const StatCard: React.FC<StatCardProps> = ({ title, value, change, icon: Icon, trend = 'neutral' }) => {
  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-sm font-medium">{title}</CardTitle>
        <Icon className="h-4 w-4 text-muted-foreground" />
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        {change && (
          <p className={`text-xs ${
            trend === 'up' ? 'text-green-600' : 
            trend === 'down' ? 'text-red-600' : 
            'text-muted-foreground'
          }`}>
            {change}
          </p>
        )}
      </CardContent>
    </Card>
  )
}

// 系统状态组件
const SystemStatus: React.FC = () => {
  const { data: componentHealth } = useQuery(
    'component-health',
    monitoringApi.getComponentHealth,
    { refetchInterval: 30000 }
  )

  const healthyCount = componentHealth?.filter(c => c.status === 'healthy').length || 0
  const totalCount = componentHealth?.length || 0

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Activity className="h-5 w-5" />
          系统状态
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">整体健康度</span>
            <span className={`text-sm font-medium ${
              healthyCount === totalCount ? 'text-green-600' : 
              healthyCount > totalCount / 2 ? 'text-yellow-600' : 
              'text-red-600'
            }`}>
              {totalCount > 0 ? `${healthyCount}/${totalCount}` : '检查中...'}
            </span>
          </div>
          
          {componentHealth?.map((component) => (
            <div key={component.name} className="flex items-center justify-between">
              <span className="text-sm">{component.name}</span>
              <div className="flex items-center gap-2">
                {component.status === 'healthy' ? (
                  <CheckCircle className="h-4 w-4 text-green-600" />
                ) : component.status === 'degraded' ? (
                  <AlertTriangle className="h-4 w-4 text-yellow-600" />
                ) : (
                  <AlertTriangle className="h-4 w-4 text-red-600" />
                )}
                <span className="text-xs text-muted-foreground">
                  {component.responseTime && `${component.responseTime}ms`}
                </span>
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}

// 最近活动组件
const RecentActivity: React.FC = () => {
  // 模拟最近活动数据
  const activities = [
    {
      id: 1,
      type: 'api_created',
      message: '创建了新的API "用户查询接口"',
      timestamp: new Date(Date.now() - 5 * 60 * 1000),
      user: '张三'
    },
    {
      id: 2,
      type: 'datasource_connected',
      message: '连接了新的数据源 "生产数据库"',
      timestamp: new Date(Date.now() - 15 * 60 * 1000),
      user: '李四'
    },
    {
      id: 3,
      type: 'plugin_installed',
      message: '安装了缓存插件',
      timestamp: new Date(Date.now() - 30 * 60 * 1000),
      user: '王五'
    },
    {
      id: 4,
      type: 'alert_triggered',
      message: 'CPU使用率超过阈值',
      timestamp: new Date(Date.now() - 45 * 60 * 1000),
      user: '系统'
    }
  ]

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Clock className="h-5 w-5" />
          最近活动
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {activities.map((activity) => (
            <div key={activity.id} className="flex items-start gap-3">
              <div className="w-2 h-2 bg-primary rounded-full mt-2 flex-shrink-0"></div>
              <div className="flex-1 min-w-0">
                <p className="text-sm">{activity.message}</p>
                <div className="flex items-center gap-2 mt-1">
                  <span className="text-xs text-muted-foreground">
                    {activity.user}
                  </span>
                  <span className="text-xs text-muted-foreground">•</span>
                  <span className="text-xs text-muted-foreground">
                    {formatDateTime(activity.timestamp, 'HH:mm')}
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}

const DashboardPage: React.FC = () => {
  const { systemMetrics, setSystemMetrics, startAutoRefresh, stopAutoRefresh } = useMonitoringStore()

  // 获取系统指标
  const { data: metrics } = useQuery(
    'system-metrics',
    monitoringApi.getSystemMetrics,
    { 
      refetchInterval: 30000,
      onSuccess: (data) => {
        setSystemMetrics(data)
      }
    }
  )

  // 获取数据源统计
  const { data: dataSourceStats } = useQuery(
    'datasource-stats',
    () => dataSourceApi.getDataSources({ page: 1, pageSize: 1 }),
    { refetchInterval: 60000 }
  )

  // 获取API统计
  const { data: apiStats } = useQuery(
    'api-stats',
    () => apiManagementApi.getApis({ page: 1, pageSize: 1 }),
    { refetchInterval: 60000 }
  )

  // 启动自动刷新
  useEffect(() => {
    startAutoRefresh(30, () => {
      // 刷新数据的回调函数
      console.log('Auto refreshing dashboard data...')
    })

    return () => {
      stopAutoRefresh()
    }
  }, [startAutoRefresh, stopAutoRefresh])

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">仪表板</h1>
          <p className="text-muted-foreground">
            数据网关系统概览和关键指标监控
          </p>
        </div>
        <Button>
          <TrendingUp className="h-4 w-4 mr-2" />
          查看详细报告
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <StatCard
          title="数据源总数"
          value={dataSourceStats?.total || 0}
          change="+2 本周新增"
          icon={Database}
          trend="up"
        />
        <StatCard
          title="API总数"
          value={apiStats?.total || 0}
          change="+5 本周新增"
          icon={Code}
          trend="up"
        />
        <StatCard
          title="活跃连接"
          value={systemMetrics?.activeConnections || 0}
          change="实时数据"
          icon={Users}
          trend="neutral"
        />
        <StatCard
          title="系统负载"
          value={systemMetrics ? formatPercentage(systemMetrics.cpuUsage / 100) : '0%'}
          change={systemMetrics?.cpuUsage && systemMetrics.cpuUsage > 80 ? '负载较高' : '运行正常'}
          icon={Activity}
          trend={systemMetrics?.cpuUsage && systemMetrics.cpuUsage > 80 ? 'down' : 'up'}
        />
      </div>

      {/* 详细信息区域 */}
      <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
        {/* 系统状态 */}
        <SystemStatus />

        {/* 最近活动 */}
        <RecentActivity />

        {/* 性能指标 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <TrendingUp className="h-5 w-5" />
              性能指标
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">CPU使用率</span>
                <span className="text-sm">
                  {systemMetrics ? formatPercentage(systemMetrics.cpuUsage / 100) : '0%'}
                </span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div 
                  className="bg-primary h-2 rounded-full transition-all duration-300"
                  style={{ width: `${systemMetrics?.cpuUsage || 0}%` }}
                ></div>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">内存使用率</span>
                <span className="text-sm">
                  {systemMetrics ? formatPercentage(systemMetrics.memoryUsage / 100) : '0%'}
                </span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div 
                  className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${systemMetrics?.memoryUsage || 0}%` }}
                ></div>
              </div>

              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">磁盘使用率</span>
                <span className="text-sm">
                  {systemMetrics ? formatPercentage(systemMetrics.diskUsage / 100) : '0%'}
                </span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div 
                  className="bg-green-500 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${systemMetrics?.diskUsage || 0}%` }}
                ></div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

export default DashboardPage
